package com.chhuang.ewcrm.comm;

import com.chhuang.ewcrm.cons.Constants;
import javafx.scene.control.Label;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static javafx.application.Platform.runLater;

/**
 * 过磅仪表串口通讯读取数据后操作类
 */
public class CommWeighValue implements CommCallBack {
    private final Logger logger = LoggerFactory.getLogger(CommWeighValue.class);

    private final Label weighLEDLabel;
    private Double lastWeigh = null;

    public CommWeighValue(Label weighLEDLabel){
        this.weighLEDLabel = weighLEDLabel;
    }
//    称重仪表数据格式：
//      [02 2B] 30 30 30 30 30 30 [30 31 42 03]
//      [开始 2B正数/2D负数][数据位000000][0位小数 校验 校验 结束]

    @Override
    public void doSuccess(String hexStr) {
        if(StringUtils.isNotEmpty(hexStr)){
            String[] dataStrs = hexStr.split(" ");
            StringBuilder str = new StringBuilder();
            for (int i=2; i<8; i++) {
                str.append(dataStrs[i].substring(1));
            }

            int s = 1;
            if("2D".equals(dataStrs[1])) s=-1;

            final double value = s*Double.parseDouble(str.toString())/1000d;
//            logger.debug("过磅重量CommWeighValue:"+value);
            runLater(() -> {
                weighLEDLabel.setText(String.valueOf(value));
                if(lastWeigh!=null && lastWeigh==value)
                    weighLEDLabel.setId("1");//稳定
                else
                    weighLEDLabel.setId("0");//不稳定
                lastWeigh = value;
            });
        }else {
            runLater(() -> {
                weighLEDLabel.setText(Constants.NO_SIGN_STR);
                weighLEDLabel.setId("-1");//无信号
                lastWeigh = null;
            });
        }
    }
}
